package com.wing.res.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.service.ProductUnitService;
import com.wing.res.model.entity.ResProductDraw;
import com.wing.res.model.entity.ResProductMoldDraw;
import com.wing.res.model.request.MoldDrawInfo;
import com.wing.res.model.request.ProcessProjectData;
import com.wing.res.model.request.TestItemData;
import com.wing.res.model.response.ResProTaskDetailVo;
import com.wing.res.model.response.ResProTaskRecordSearchVo;
import com.wing.res.model.response.ResProTaskSearchVo;
import com.wing.res.service.ResProEchnologyParamService;
import com.wing.res.service.ResProTaskService;
import com.wing.res.service.ResProductDrawService;
import com.wing.res.service.ResProductMoldDrawService;
import com.wing.sell.model.entity.OrderProEnclosure;
import com.wing.sell.service.OrderProEnclosureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品工艺路线
 *
 * @version 1.1.0
 * @Author hz
 * @Date 2024-09-24 17:08
 **/
@Slf4j
@Validated
@Api(value = "产品规划-工艺规划任务", tags = "#/res/planning/processPlan/processLog")
@RestController("resProEchnologyParamRecordController")
@RequestMapping("res/admin/echnologyParamRecord")
public class ResProEchnologyParamRecordController {


    @Resource
    private ResProTaskService resProTaskService;

    @Resource
    private ProductUnitService productUnitService;

    @Autowired
    private ResProEchnologyParamService resProEchnologyParamService;

    @Resource
    private ResProductDrawService resProductDrawService;

    @Resource
    private ResProductMoldDrawService resProductMoldDrawService;


    @ApiOperation(value = "查询-Bom记录", notes = "查询-bom记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ResProTaskRecordSearchVo> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long productTypeId
            ,Long customerId
            ,String customerProCode
            ,String productStatus
            ,String customerProFigure
            ,String givenStartTimed
    ) {
        Page<ResProTaskRecordSearchVo> pg = new Page<>(page, limit);
        Map<String,Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("customerProCode", customerProCode);
        map.put("productStatus", productStatus);
        if (StrUtil.isNotEmpty(givenStartTimed)){
            // 使用 split 方法分割字符串
            String[] dates = givenStartTimed.split(" 至 ");
            // 获取开始和结束日期
            String startDate = dates[0];
            String endDate = dates[1];
            map.put("givenStartTime", startDate);
            map.put("givenEndTime", endDate);
        }
        map.put("customerProFigure", customerProFigure);
        map.put("productTypeId", productTypeId);
        Page<ResProTaskRecordSearchVo> list = resProEchnologyParamService.pageList4app(pg, map);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 初始化任务详情
     * @param taskId
     * @return
     */
    @ApiOperation(value = "查看研发任务详情", notes = "查看")
    @GetMapping("/detail/{taskId}/{recordId}")
    public JsonResult resProTaskDetail(@PathVariable("taskId") String taskId,@PathVariable("recordId") String recordId) {
        ResProTaskDetailVo taskDetail =  resProTaskService.resProTaskDetail(taskId);
        if (taskDetail == null) {
            return JsonResult.fail("获取详情失败！");
        }
        //是否关联新产品
        if (StrUtil.isNotEmpty(taskDetail.getIsUseOrAdd())){
            taskDetail.setIsUseOrAdd(ProductEnum.ReviewUseOrNewEmum.getNameByCode(taskDetail.getIsUseOrAdd()));
        }
        //赋值结果
        if (taskDetail.getProductTypeId()!=null){
            QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("type", 0);
            wrapper.eq("product_type", taskDetail.getProductTypeId());
            wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
            wrapper.eq("is_base_unit", "1");
            ProductUnitInfo productUnitInfo = productUnitService.getOne(wrapper);
            //赋值基础单位
            if (ObjectUtil.isNotEmpty(productUnitInfo)) {
                taskDetail.setInUnitName(productUnitInfo.getName());
            }
        }
        QueryWrapper<ResProductDraw> queryWrapper = new QueryWrapper<ResProductDraw>();
        queryWrapper.eq("is_default",'1');
        queryWrapper.eq("product_detail_id",taskDetail.getProductDetailId());
        queryWrapper.eq("task_id",taskDetail.getId());
        ResProductDraw one = resProductDrawService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one) && one.getIsRelevance().equals(MaintenanceEnum.DrawTypeEnum.CPTZ.getCode())){
            QueryWrapper<ResProductMoldDraw> moldWrapper = new QueryWrapper<ResProductMoldDraw>();
            moldWrapper.eq("is_default",'1');
            moldWrapper.eq("draw_id",one.getId());
            ResProductMoldDraw draw = resProductMoldDrawService.getOne(moldWrapper);
            MoldDrawInfo info = new MoldDrawInfo();
            BeanUtil.copyProperties(draw, info,true);
            one.setMoldDrawInfo(info);
        }
        //初始化工序信息
        List<ProcessProjectData> oldVersionInfo = resProEchnologyParamService.getVersionInfoBy(recordId);
        taskDetail.setProcessProjectData(oldVersionInfo);
        taskDetail.setDrawInfo(one);
        return JsonResult.success("获取成功！",taskDetail);
    }
}
